if(!window.mc){
	window.mc = function(){};
}
mc.cmd = function(){};

mc.cmd.init = function(target){
	this.main = target;
	this.cache = {};
	this.re = /\/?([^\?]+)(?:\?(.+))?/;
	target.delegate("a.mc","click",function(event){
		mc.cmd.run($(this).attr("href"));
		return false;
	});
}
mc.cmd.run = function(str){
	try {
		var cmd = mc.cmd.re.exec(str);
		var func = cmd[1];
		var param = [];
		if(cmd[2]){
			param = cmd[2].split(";");
		}
		if(!this.cache[func]){
			if(this[func] && typeof(this[func])=="function"){
				this.cache[func] = [this[func],mc.cmd,0];
			}else{
				var cmd_path = func.split(".");
				var target = window;
				var prev;
				for(var pos=0; pos < cmd_path.length; pos++){
					if(!target[cmd_path[pos]]){
						target = undefined;
						break;
					}
					prev = target;
					target = target[cmd_path[pos]];
				}
				if(target && typeof(target)=="function"){
					this.cache[func] = [target,prev,0];
				}
			}
		}
		if(this.cache[func]){
			dbg("called: " + func + " times: " + (++this.cache[func][2]));
			this.cache[func][0].apply(this.cache[func][1],param);
			return false;
		}else{
			throw new Error("bad command '" + func + "'");
		}
		
	}catch(e){
		mc.tape.put_console("error: " + e.message);
	}
	return false;
}

mc.cmd.draw_main = function(template,data){
	$.tmpl(template,data).appendTo(this.get_main().empty());
}
mc.cmd.draw_left = function(template,data){
	$.tmpl(template,data).appendTo(this.get_left().empty());
}
mc.cmd.draw_right = function(template,data){
	$.tmpl(template,data).appendTo(this.get_right().empty());
}
mc.cmd.get_main = function(){
	return this.main;
}
mc.cmd.get_left = function(){
	return this.main.find("> div > div:eq(0)");
}
mc.cmd.get_left_inner = function(pos){
	if(!pos){
		pos = 0;
	}
	return this.main.find("> div > div:eq(0) > div:eq(" + pos + ")");
}
mc.cmd.get_right = function(){
	return this.main.find("> div > div:eq(1)");
}
mc.cmd.get_right_inner = function(pos){
	if(!pos){
		pos = 0;
	}
	return this.main.find("> div > div:eq(1) > div:eq(" + pos + ")");
}
mc.cmd.message = function(msg){
	mc.tape.put_console(msg);
}
mc.cmd.nop = function(){
}
